Skip to content
This repository has been archived by the owner on Feb 4, 2022. It is now read-only.

Commit

Permalink
Merge pull request #7 from martpie/master
Browse files Browse the repository at this point in the history
Get changes from Martpie
  • Loading branch information
jamesgorrie authored Feb 28, 2019
2 parents 028558e + ca563f4 commit f42c92a
Show file tree
Hide file tree
Showing 8 changed files with 1,636 additions and 53 deletions.
31 changes: 31 additions & 0 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
version: 2
jobs:
test:
docker:
- image: circleci/node:10
working_directory: ~/lib

steps:
- checkout

- restore_cache:
keys:
- v1-dependencies-{{ checksum "package.json" }}
- v1-dependencies-

- run: npm install

- save_cache:
paths:
- node_modules
key: v1-dependencies-{{ checksum "package.json" }}

- run:
name: "Lint check: JS"
command: npm run lint

workflows:
version: 2
test:
jobs:
- test
3 changes: 3 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "semistandard"
}
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2018 Pierre de la Martinière

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
118 changes: 118 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Next.js + Transpile `node_modules`

Transpile untranspiled modules from `node_modules`.
Makes it easy to have local libraries and keep a slick, manageable dev experience.

## Compatibility table

| Next.js version | Plugin version |
|-----------------|----------------|
| Next.js 8 | 2.x |
| Next.js 6 / 7 | 1.x |

## Installation

```
npm install --save next-transpile-modules
```

or

```
yarn add next-transpile-modules
```

## Usage

Classic:

```js
// next.config.js
const withTM = require('next-transpile-modules');

module.exports = withTM({
transpileModules: ['somemodule', 'and-another']
});
```

**note:** please declare `withTM` as your last plugin (the "most nested" one).

Example with `next-typescript`:

```js
const withTypescript = require('@zeit/next-typescript');
const withTM = require('next-transpile-modules');

module.exports = withTypescript(
withTM({
transpileModules: ['somemodule', 'and-another']
})
);
```

With `next-compose-plugins`:

```js
const withPlugins = require('next-compose-plugins');

const withTypescript = require('@zeit/next-typescript');
const withTM = require('next-transpile-modules');

module.exports = withPlugins([
[withTM, {
transpileModules: ['some-module', 'and-another'],
}],
withTypescript,
], {
// ...
});
```

## FAQ

### What is the difference with `@weco/next-plugin-transpile-modules`?

- it is maintained, `@weco`'s seems dead
- it supports TypeScript

### I have trouble making it work with Next.js 7

Next.js 7 introduced Webpack 4 and Babel 7, [which changed a couple of things](https://github.com/zeit/next.js/issues/5393#issuecomment-458517433), especially for TypeScript and Flow plugins.

If you have a transpilation error when loading a page, check that your `.babelrc`/`babel.config.js` is up to date and valid, [you may have forgotten a preset](https://github.com/martpie/next-transpile-modules/issues/1#issuecomment-427749256) there.

### I have trouble with Yarn and hot reloading

If you add a local library (let's say with `yarn add ../some-shared-module`), Yarn will copy those files by default, instead of symlinking them. So your changes to the initial folder won't be copied to your Next.js `node_modules` directory.

You can go back to `npm`, or use Yarn workspaces. See [an example](https://github.com/zeit/next.js/tree/canary/examples/with-yarn-workspaces) in the official Next.js repo.

### I have trouble making it work with Lerna

Lerna's purpose is to publish different packages from a monorepo, **it does not help for and does not intend to help local development with local modules**.

This is not coming from me, but [from Lerna's maintainer](https://github.com/lerna/lerna/issues/1243#issuecomment-401396850).

So you are probably [using it wrong](https://github.com/martpie/next-transpile-modules/issues/5#issuecomment-441501107), and I advice you to use `npm` or Yarn workspaces instead.

### But... I really need to make it work with Lerna!

You may need to tell your Webpack configuration how to properly resolve your scoped packages, as they won't be installed in your Next.js directory, but the root of your Lerna setup.

```js
const withTM = require('next-transpile-modules');

module.exports = withTM({
transpileModules: ['@your-project/shared', '@your-project/styleguide'],
webpack: (config, options) => {
config.resolve.alias = {
...config.resolve.alias,
// Will make webpack look for these modules in parent directories
'@your-project/shared': require.resolve('@your-project/shared'),
'@your-project/styleguide': require.resolve('@your-project/styleguide'),
// ...
};
return config;
},
});
```
76 changes: 54 additions & 22 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,73 @@
module.exports = (nextConfig = {}) => {
const path = require('path');

/**
* Stolen from https://stackoverflow.com/questions/10776600/testing-for-equality-of-regular-expressions
*/
function regexEqual (x, y) {
return (x instanceof RegExp) && (y instanceof RegExp) &&
(x.source === y.source) && (x.global === y.global) &&
(x.ignoreCase === y.ignoreCase) && (x.multiline === y.multiline);
}

const { transpileModules = [] } = nextConfig
const includes = transpileModules.map(module => (new RegExp(`${module}(?!.*node_modules)`)))
const excludes = transpileModules.map(module => (new RegExp(`node_modules(?!\/${module}(?!.*node_modules))`)))
/**
* Actual Next.js plugin
*/
module.exports = (nextConfig = {}) => {
const { transpileModules = [] } = nextConfig;
const includes = transpileModules.map(module => (new RegExp(`${module}(?!.*node_modules)`)));
const excludes = [new RegExp(`node_modules(?!/(${transpileModules.join('|')})(?!.*node_modules))`)];

return Object.assign({}, nextConfig, {
webpack(config, options) {
webpack (config, options) {
// Safecheck for Next < 5.0
if (!options.defaultLoaders) {
throw new Error(
'This plugin is not compatible with Next.js versions below 5.0.0 https://err.sh/next-plugins/upgrade'
)
);
}

config.resolve.symlinks = false
// Avoid Webpack to resolve transpiled modules path to their real path
config.resolve.symlinks = false;

config.externals = config.externals.map(external => {
if (typeof external !== 'function') return external
return (ctx, req, cb) =>
(Boolean(includes.find(include => include.test(req))) ? cb() : external(ctx, req, cb))
})

if (typeof external !== 'function') return external;
return (ctx, req, cb) => {
return includes.find(include =>
req.startsWith('.')
? include.test(path.resolve(ctx, req))
: include.test(req)
)
? cb()
: external(ctx, req, cb);
};
});

// Add a rule to include and parse all modules
config.module.rules.push({
test: /\.+(js|jsx)$/,
test: /\.+(js|jsx|ts|tsx)$/,
loader: options.defaultLoaders.babel,
include: includes
})
});

if (typeof nextConfig.webpack === 'function') {
return nextConfig.webpack(config, options)
return nextConfig.webpack(config, options);
}

return config
return config;
},

webpackDevMiddleware(config) {
const ignored = [config.watchOptions.ignored[0]].concat(excludes)
config.watchOptions.ignored = ignored
return config
// webpackDevMiddleware needs to be told to watch the changes in the
// transpiled modules directories
webpackDevMiddleware (config) {
// Replace /node_modules/ by the new exclude RegExp (including the modules
// that are going to be transpiled)
// https://github.com/zeit/next.js/blob/815f2e91386a0cd046c63cbec06e4666cff85971/packages/next/server/hot-reloader.js#L335
const ignored = config.watchOptions.ignored.filter(
regexp => !regexEqual(regexp, /[\\/]node_modules[\\/]/)
).concat(excludes);

config.watchOptions.ignored = ignored;
return config;
}
})
}
});
};
Loading

0 comments on commit f42c92a

Please sign in to comment.